package com.ubs.training.server.dao.impl.hbm;

import com.ubs.training.server.dao.ProductDao;
import com.ubs.training.server.dao.model.Client;
import com.ubs.training.server.dao.model.Product;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xubuntu
 * Date: 8/27/12
 * Time: 10:19 AM
 * To change this template use File | Settings | File Templates.
 */
@Repository("hbmProductDao")
public class HbmProductDao implements ProductDao{

    private SessionFactory factory;

    private HibernateTemplate tpl;

    public SessionFactory getFactory() {
        return factory;
    }

    @Autowired
    public void setFactory(SessionFactory factory) {
        tpl = new HibernateTemplate(factory);
        this.factory = factory;
    }

    @Override
    public List<Product> getAll() {
        return tpl.loadAll(Product.class);
    }

    @Override
    public Product getById(int id) {
        return tpl.load(Product.class, id);
    }

    @Override
    public boolean add(Product product) {
        tpl.save(product);
        return true;
    }

    @Override
    public boolean update(Product product) {
        tpl.merge(product);
        tpl.update(product);
        return true;
    }

    @Override
    public boolean remove(Product product) {
        tpl.merge(product);
        tpl.delete(product);
        return true;
    }

    @Override
    public List<Product> getByClientId(int clientId) {

        return tpl.findByCriteria(DetachedCriteria.forClass(Client.class).add(Property.forName("id").eq(clientId)));
    }

    public void reset(Object obj){
        factory.getCache().evictEntityRegion(obj.getClass());
        Session session = factory.getCurrentSession();
        session.flush();
        session.clear();
    }
}
